/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2020/8/28 0028
 */
package com.yao.auth.handler;

import com.yao.auth.config.CustomSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登陆成功处理类
 * 
 * @author yaoyuming
 * @date 2020/8/28 0028 11:07
 */
@Slf4j
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    @Autowired
    private CustomSecurityProperties customSecurityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authen) throws IOException {
        log.info("登陆成功,{},跳转首页:{}", authen, customSecurityProperties.getHomePage());
        redirectStrategy.sendRedirect(request, response, customSecurityProperties.getHomePage());

        // 跳转访问页面
        // SavedRequest savedRequest = requestCache.getRequest(request, response);
        // log.info("跳转访问页面:{}", savedRequest.getRedirectUrl());

        // 实际上应该跳转到主页，而不是最初访问的.html后缀的地址，不然就可以绕过主页去到其他界面，这样是不符合实际业务的
    }
}